package com.hkts.beltweigher.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * MyChannelHandlerPool
 * 通道组池，管理所有websocket连接
 */
public class MyChannelHandlerPool {

    public MyChannelHandlerPool(){}
    //pc用的通道
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    //小程序用的通道
    public static ChannelGroup wechatChannelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    // 用户
    private static Map<String, ChannelHandlerContext> userChannel = new ConcurrentHashMap<>();
    private static Map<String, String> userChannelId = new ConcurrentHashMap<>();
    // 群组
    private static Map<String, ChannelGroup> channelGroupMap = new ConcurrentHashMap<>();

    public static void addChannel(String userId, ChannelHandlerContext channel) {
        userChannel.put(userId, channel);
        userChannelId.put(channel.channel().id().toString(), userId);
    }

    public static void removeChannel(String channelId){
        String userId = userChannelId.get(channelId);
        if (null == userId) return;
        userChannel.remove(userId);
    }

    public static void removeUserChannelByUserId(String userId){
        userChannel.remove(userId);
    }

    public static ChannelHandlerContext getChannel(String userId) {
        return userChannel.get(userId);
    }
    public static String getUserId(String channelId){
        String userId = userChannelId.get(channelId);
        return userId;
    }
    public static Map<String, ChannelHandlerContext> getAllChannel() {
        return userChannel;
    }


}